package com.wjjun.basemvpvm.utils;

import android.text.InputFilter;
import android.text.Spanned;

import java.io.UnsupportedEncodingException;

public class EmojiInputFilter implements InputFilter {

    public final int VALID_STRING = 0;
    public final int NULL_STRING = -1;
    public final int CONTAIN_INVALID_CHAR = -2;


    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        int checkResult = isContainInvalidChar(source.toString());
        if (checkResult == CONTAIN_INVALID_CHAR) {
            return "";
        }
        return null;
    }


    /**
     * 是否包含特殊字符，包括表情
     *
     * @param valueString
     * @return
     */
    public int isContainInvalidChar(final String valueString) {
        if (valueString == null || valueString.isEmpty()) {
            return NULL_STRING;
        } else if (valueString.contains("@%")) {
            return CONTAIN_INVALID_CHAR;
        } else {
            // 由于服务器不支持4字节的UTF-8编码，因此在此限制
            try {
                byte[] bytes = valueString.getBytes("UTF-8");
                for (byte by : bytes) {
                    if ((by & 0xF0) == 0xF0) {  // 以0b11110xxx开始的一定是4字节的UTF-8字符
                        return CONTAIN_INVALID_CHAR;
                    }
                }
            } catch (UnsupportedEncodingException e) {
                return CONTAIN_INVALID_CHAR;
            }
        }

        return VALID_STRING;
    }
}
